const jwt = require('jsonwebtoken')
const createToken = (username) => {
  const token = jwt.sign(
    { username },
    'window-Token',
    { expiresIn: 60 * 60 * 24 * 3 }
  )
  return token
}

const auth = (ctx, next) => {
  const { authorization } = ctx.request.header
  const token = authorization.replace('Bearer ', '')
  try {
    const user = jwt.verify(token, 'window-Token')
    ctx.user = user
  } catch(err) {
    ctx.throw(401, err.message)
  }
}

module.exports = { createToken, auth }
